package com.barradata.app0624.modules.login

import android.content.Context
import android.content.Intent
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.common.base.BaseActivity
import com.barradata.common.utils.ToastUtils
import com.barradata.app0624.data.UserDataManager
import com.barradata.app0624.modules.web.EventType
import com.barradata.app0624.modules.web.WebCallbackEvent
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.jakewharton.rxbinding3.widget.textChanges
import io.reactivex.functions.Consumer
import io.reactivex.rxkotlin.Observables
import kotlinx.android.synthetic.main.login_debug_activity.*

/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/4 13:54
 **/

class DebugLoginActivity : BaseActivity() {
    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, DebugLoginActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId() = R.layout.login_debug_activity

    override fun initView() {
        Observables.combineLatest(user_name_et.textChanges(), password_et.textChanges()
        ) { username, password ->
            username.isNotEmpty() && password.isNotEmpty()
        }.subscribe {
            login_button.isEnabled = it
        }.autoClean()

        login_button.clickV().subscribe {
            doLogin()
        }.autoClean()
        register_button.clickV().subscribe {
            finish()
        }.autoClean()
    }

    private fun doLogin() {
        val userName = user_name_et.text.toString()
        val password = password_et.text.toString()
        showLoadingView()

        ApiService.login(userName, password)
                .doOnSubscribe {  }
                .subscribe({
            dismissLoadingView()
            if (it.isRel) {
                UserDataManager.token = it.data.token
                requestUserStatus()
            } else {
                ToastUtils.showShort(it.message)
            }
        }, {
            dismissLoadingView()
            logD(it.message.toString())
        }).autoClean()


    }

    private fun requestUserStatus() {
        ApiService.getStatus().subscribe({
            UserDataManager.uuid = it.data.userUuid
            UserDataManager.addressBookUuid = it.data.addressBookUuid
            if (UserDataManager.token.isEmpty()) {
                ToastUtils.showShort(R.string.token_is_null)
                return@subscribe
            }
            ToastUtils.showShort(R.string.login_page_login_success)
            RxBus.post(WebCallbackEvent(EventType.FROM_LOGIN))
            finish()
        }, {
            ToastUtils.showShort(it.message.toString())
        }).autoClean()
    }


}